<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>取消请求</title>
  <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>
</head>

<body>
  <button>发送请求</button>
  <button>取消请求</button>

  <script>
    let btns = document.querySelectorAll('button');
    // 定义取消函数
    let cancel

    btns[0].onclick = async function () {
      axios.post('http://localhost:8081/delay-server/123', null, {
        cancelToken: new axios.cancelToken((c) => { // c是内部定义并传递过来取消请求的函数  回调函数在发请求前调用
          //保存取消请求的函数
          cancel = c;
        })
      })
    };

    btns[1].onclick = function () {
      //调用取消函数来取消请求
      cancel && cancel();
    };
  </script>
</body>

</html>